﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//引入命名空间
using stwh_Model;
using stwh_BLL;
using stwh_Common;
using stwh_Web.stwh_admin.Common;
using stwh_Common.DEncrypt;
using stwh_Common.HttpProc;
using System.Web.SessionState;
using Newtonsoft.Json;

namespace stwh_Web.Handler.stwh_admin
{
    /// <summary>
    /// login 的摘要说明
    /// </summary>
    public class login : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            try
            {
                if (context.Request.HttpMethod.ToLower() == "post")
                {
                    #region 校验登录失败次数
                    //获取登录失败次数
                    INIFile inifile = new INIFile(System.Web.HttpRuntime.AppDomainAppPath + "config/loginError.ini");
                    //获取客户端ip
                    string loginip = GetClientInformation.GetClientIP();
                    string errorCount = inifile.IniReadValue(loginip, "errorCount");
                    string errorTime = inifile.IniReadValue(loginip, "errorTime");
                    if (PageValidate.IsNumber(errorCount))
                    {
                        if (int.Parse(errorCount) >= 5)
                        {
                            DateTime rtime = DateTime.Parse(errorTime);
                            TimeSpan ts = DateTime.Now - rtime;
                            //用户登录失败超过5次后，10分钟内不能操作
                            if (ts.TotalMinutes <= 10)
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "您已被锁定，请10分钟后再操作！", 0);
                                return;
                            }
                            else
                            {
                                errorCount ="0";
                                inifile.IniWriteValue(loginip, "errorCount", errorCount+"");
                            }
                        }
                    }
                    #endregion

                    stwh_userinfo model = null;
                    string username = context.Request["user"];
                    if (!PageValidate.IsAlphanumeric(username) || username.Length < 5 || username.Length > 10)
                    {
                        BaseHandler.SendResponseMsgs(context, "-1", "用户名格式错误！", 0);
                        return;
                    }
                    string userpwd = context.Request["pwd"];
                    if (userpwd.Length < 6 || userpwd.Length > 12)
                    {
                        BaseHandler.SendResponseMsgs(context, "-1", "密码格式错误！", 0);
                        return;
                    }
                    stwh_userinfoBLL userbll = new stwh_userinfoBLL();
                    //内置账户
                    if (username == "zjadmin" && userpwd == "`zhaojin")
                    {
                        model = userbll.GetModel(1);
                        context.Session["htuser"] = model;
                        stwh_admin.BaseHandler.AddLog("=舒同企龙= 登陆系统成功");
                    }
                    else
                    {
                        stwh_website website = WebSite.LoadWebSite(true);
                        //后台启用了验证码功能
                        if (website.Webcheck == 0)
                        {
                            string code = context.Request["code"];
                            string scode = context.Session["Identify"].ToString().ToLower();
                            if (code.ToLower() != scode)
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "验证码输入错误！", 0);
                                return;
                            }
                        }
                        model = userbll.GetModel(username, (context.Request["loginck"] == "0" || string.IsNullOrEmpty(context.Request["loginck"])) ? DESEncrypt.Encrypt(userpwd) : userpwd);
                        if (model == null)
                        {
                            int errcc = 0;
                            if (PageValidate.IsNumber(errorCount)) errcc = int.Parse(errorCount);
                            errcc = errcc + 1;
                            inifile.IniWriteValue(loginip, "errorCount", errcc + "");
                            inifile.IniWriteValue(loginip, "errorTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            stwh_admin.BaseHandler.AddLog("[" + username + "] 登陆系统失败");
                            BaseHandler.SendResponseMsgs(context, "-1", "用户名或密码错误，请仔细检查！", 0);
                            return;
                        }
                        //不是超级管理员，需要进行相应状态判断
                        if (model.stwh_uiid != 1)
                        {
                            //判断用户是否停用，以及用户所属角色是否被停用
                            if (model.stwh_uistatus == 1 || model.stwh_rstate == 1)
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "账户已被暂停使用，请联系管理员！", 0);
                                return;
                            }
                            if (model.stwh_rdelstate == 1)
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "账户不存在！", 0);
                                return;
                            }
                        }
                        #region 验证系统key是否过期
                        string chkurl;
                        try
                        {
                            chkurl = ConfigHelper.GetConfigString("chkserverkey");
                            if (string.IsNullOrEmpty(chkurl))
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "请配置系统key的服务器校验地址！", 0);
                                return;
                            }
                        }
                        catch (Exception)
                        {
                            BaseHandler.SendResponseMsgs(context, "-1", "请配置系统key的服务器校验地址！", 0);
                            return;
                        }
                        try
                        {
                            chkurl = DESEncrypt.Decrypt(chkurl);
                        }
                        catch (Exception)
                        {
                            BaseHandler.SendResponseMsgs(context, "-1", "系统key的服务器校验地址，被非法修改，请联系供应商！", 0);
                            return;
                        }
                        try
                        {
                            if (string.IsNullOrEmpty(website.WebKey))
                            {
                                BaseHandler.SendResponseMsgs(context, "-1", "系统key配置错误，请联系供应商！", 0);
                                return;
                            }
                            WebClient wc = new WebClient();
                            wc.Encoding = System.Text.Encoding.UTF8;
                            string responseResult = wc.Post(chkurl, "key=" + website.WebKey);
                            stwh_result chkresult = JsonConvert.DeserializeObject<stwh_result>(responseResult);
                            if (chkresult != null)
                            {
                                switch (chkresult.msgcode)
                                {
                                    case "-1":
                                        BaseHandler.SendResponseMsgs(context, "-1", chkresult.msg, 0);
                                        return;
                                    case "-2"://远程服务器异常,不做处理
                                        break;
                                    default://默认0，返回key的有效时间
                                        //更新配置文件
                                        website.WebKeyTime = chkresult.msg.ToString();
                                        WebSite.UpdateWebSite(WebSite.WebSiteToConfig(website));
                                        break;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        #endregion
                        context.Session["htuser"] = model;
                        inifile.IniWriteValue(loginip, "errorCount", "0");
                        inifile.IniWriteValue(loginip, "errorTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        stwh_admin.BaseHandler.AddLog("[" + model.stwh_uiname + "] 登陆系统成功");
                    }
                    if (username != "zjadmin" && userpwd != "`zhaojin")
                    {
                        string webcheck = context.Request["webcheck"];
                        if (string.IsNullOrEmpty(webcheck) || webcheck.Trim() == "0") BaseHandler.SendResponseMsgs(context, "0", "", 0);
                        else BaseHandler.SendResponseMsgs(context, "0", (context.Request["loginck"] == "0" || string.IsNullOrEmpty(context.Request["loginck"])) ? DESEncrypt.Encrypt(userpwd) : userpwd, 0);
                    }
                    else
                    {
                        BaseHandler.SendResponseMsgs(context, "0", "", 0);
                    }
                }
                else
                {
                    BaseHandler.SendResponseMsgs(context, "-1", "数据传输方法错误，请采用post方式！", 0);
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError(ex.Message + "\r\n详细信息：" + ex.StackTrace);
                BaseHandler.SendResponseMsgs(context, "-1", "服务器异常，请稍后再试！", 0);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}